package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.hst.ThreeDesUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONObject
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.elite.EliteBean

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat
import java.time.Instant
import cn.com.kh.getProperty;
import com.huasheng.passwordencrypt.DecryptUtil

/**
 * 华盛通开户名单下发线程任务
 */

public class autoHSTCustIssued implements EliteThreadInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoHSTCustIssued.class);

    public int doCallBack(EliteBean eliteBean, String content) {

        // 查询待处理名单 grep -E 'autoHSTCustIssued|待处理名单线程Guid'
        log.debug("待处理名单线程Guid：" + content);

        String flag_SQL = "update EliteThread set status='1' where Content = '" + content + "'";
        int sqlResult = eliteBean.update(flag_SQL, "dataSource");
        log.debug("待处理名单线程Guid 标记处理中(最大化避免重复执行风险) 更新结果:" + sqlResult);

        List accountList = eliteBean.chaxun_sql("Select Rec_Id, Customerid, Customername, Gender, Phone, Accounttype, register_id, Registertime, Opentime, Inviter_Hstno, Inviter_Name, Inviter_Type, registerstatus From Account_Information Where Batch_Guid = '" + content + "'", "dataSource");
        for (int i = 0; i < accountList.size(); i++) {
            long startTime = System.currentTimeMillis();
            Map accountMap = accountList.get(i);

            String Rec_Id = accountMap.get("Rec_Id");//处理任务主键
            String Customerid = accountMap.get("Customerid");//华盛号
            String register_id = accountMap.get("register_id");//注册渠道id
            String Inviter_Hstno = accountMap.get("Inviter_Hstno");//邀约华盛号
            String registerstatus = accountMap.get("registerstatus");//开户状态 1已开户 2未开户（注册）3未开户（暂存）4未开户（审核中） 5未开户（暂存申请） 6已注销
            String Phone = accountMap.get("Phone");//手机号码

            String Rule_Id = null;
            String r_Control_Id = null;
            String r_Rolegroup_Id = null;
            String r_Staff_Id = null;
            String counselor_id = null;

            // 查询名单是否已经存在
            def Customer_Guid;
            def distributionstatus;//分配状态
            List custCountList = eliteBean.chaxun_sql("Select Customer_Guid,distributionstatus From Customer where Customer_Id = '" + Customerid + "' ", "dataSource");
            if (custCountList.size() > 0) {
                Customer_Guid = custCountList.get(0).get("Customer_Guid");
                distributionstatus = custCountList.get(0).get("distributionstatus");
                log.debug("当前客户id：" + Customer_Guid);
                log.debug("分配状态：" + distributionstatus);
            }
            List objcustCountList = eliteBean.chaxun_sql("Select o.Customer_Guid as Customer_Guid From Customer c left join objective o  on c.customer_guid=o.customer_guid Where 1=1  and c.Customer_Id = '" + Customerid + "' and o. Map_Id='MY48ZX'", "dataSource");

            if (objcustCountList.size() <= 0) {
                // 通过名单信息中渠道在规则表中找到优先级最高的规则
                String ruleCheckSQL = "Select Rule_Id, Rule_Name, Rolegroup, Staff_Id, Order_Adjustment,weight,allocation_method From Hst_Rule_Issue Where Rule_State = 1 And Find_In_Set('" + register_id + "', Code_Id) > 0 Order By Order_Adjustment Limit 1";

                List ruleCheckList = eliteBean.chaxun_sql(ruleCheckSQL, "dataSource");
                if (ruleCheckList.size() > 0) {
                    Map ruleCheckMap = ruleCheckList.get(0);
                    Rule_Id = ruleCheckMap.get("Rule_Id");
                    String Rule_Name = ruleCheckMap.get("Rule_Name");
                    String Rolegroup = ruleCheckMap.get("Rolegroup");
                    String Staff_Id = ruleCheckMap.get("Staff_Id");
                    String Order_Adjustment = ruleCheckMap.get("Order_Adjustment");
                    String weight = ruleCheckMap.get("weight");
                    String allocation_method = ruleCheckMap.get("allocation_method");
                    log.debug("[输出获取规则信息] 规则ID:" + Rule_Id + " 规则名:" + Rule_Name + " 下发组:" + Rolegroup + " 下发人:" + Staff_Id + " 优先级:" + Order_Adjustment + " 权重:" + weight + " 类型:" + allocation_method);

                    //判断规则配置不能为空 则执行
                    if (weight != null && allocation_method != null) {
                        // 初始化规则下发
                        ruleAssignInit(eliteBean, Rule_Id, weight, allocation_method, Rolegroup, Staff_Id);

                        String getAssginStaffSQL;
                        List getAssginStaffList;

                        if (allocation_method == "按人员分配") {
                            // 取当前名单下发最少的坐席（不支持一人多组）
                            getAssginStaffSQL = "Select R1.Rec_Id, R3.DEFAULTROLEGROUP AS Rolegroup_Id, R1.Staff_Id, R3.counselor_id" +
                                    "  From Hst_Rule_Issue_Control R1" +
                                    "  Left Join Staff R3" +
                                    "    On R1.Staff_Id = R3.Staff_Id" +
                                    " Where Rule_Id = " + Rule_Id + "" +
                                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')" +
                                    " Order By round(if(Assign_Num=0,0.5,Assign_Num)/proportion,4),proportion,rand() Limit 1";
                            getAssginStaffList = eliteBean.chaxun_sql(getAssginStaffSQL, "dataSource");
                        } else if (allocation_method == "按组分配") {
                            // 取当前名单下发最少的坐席（支持一人多组） 想查询组 在排序组内得到最少的
                            getAssginStaffSQL = "Select DISTINCT R1.Rec_Id, R1.Rolegroup_Id AS Rolegroup_Id, R1.Staff_Id, R3.counselor_id" +
                                    "  From Hst_Rule_Issue_Control R1" +
                                    "  Left Join Staff R3" +
                                    "    On R1.Staff_Id = R3.Staff_Id" +
                                    " Where Rule_Id = " + Rule_Id + "" +
                                    " 	And Rolegroup_Id = (select Rolegroup_Id " +
                                    "   							from Hst_Rule_Issue_Control " +
                                    "   					Where Rule_Id = " + Rule_Id + "" +
                                    "  						 group by  Rolegroup_Id " +
                                    "  						 ORDER BY avg(round(if(assign_num=0,0.5,assign_num)/proportion,4)) Limit 1)" +
                                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')" +
                                    " Order By Assign_Num,rand() Limit 1";
                            getAssginStaffList = eliteBean.chaxun_sql(getAssginStaffSQL, "dataSource");
                        }


                        if (getAssginStaffList.size() > 0) {
                            Map getAssginStaffMap = getAssginStaffList.get(0);
                            r_Control_Id = getAssginStaffMap.get("Rec_Id");
                            r_Rolegroup_Id = getAssginStaffMap.get("Rolegroup_Id");
                            r_Staff_Id = getAssginStaffMap.get("Staff_Id");
                            counselor_id = getAssginStaffMap.get("counselor_id");// TODO 调用绑定接口是能与内部系统同步的员工ID

                            log.debug("[当前名单下发人信息] Rolegroup_Id:" + r_Rolegroup_Id + " Staff_Id:" + r_Staff_Id);
                        } else {
                            r_Rolegroup_Id = '';
                            r_Staff_Id = '';
                            log.debug("[当前名单下发人信息] 无组别人员 默认不分配 进入未分配数据池！");
                        }
                    } else {
                        r_Rolegroup_Id = '';
                        r_Staff_Id = '';
                        log.debug("[当前名单下发人信息] 规则配置为空 默认不分配 进入未分配数据池！");
                    }


                } else {// TODO 默认名单下发人需要结合业务实际修改
                    def obleaderSQL = "Select r_Rolegroup_Id, r_Staff_Id, counselor_id From hst_ob_leader Limit 1";
                    def obleaderresult = eliteBean.chaxun_sql(obleaderSQL, "dataSource");
                    if (obleaderresult.size() > 0) {
                        r_Rolegroup_Id = obleaderresult.get(0).get("r_Rolegroup_Id");
                        r_Staff_Id = obleaderresult.get(0).get("r_Staff_Id");
                        counselor_id = obleaderresult.get(0).get("counselor_id");
                    } else {// TODO 系统层面兜底
                        r_Rolegroup_Id = "";
                        r_Staff_Id = "";
                        counselor_id = "";
                    }
                    r_Control_Id = "-9999";
                    log.debug("[输出获取信息] r_Control_Id:" + r_Control_Id + " r_Rolegroup_Id:" + r_Rolegroup_Id + " r_Staff_Id:" + r_Staff_Id + " counselor_id:" + counselor_id);
                    log.debug("未查询到规则，名单下发到默认管理员，由管理员手动下发");
                }

                //判断当前客户是否属于邀约客户，属于则将名单直接下发给对应服务顾问
                if (Inviter_Hstno != '' && Inviter_Hstno != null) {
                    String fwgw_id, staff_id, rolegroup_id, control_id = "";
                    //查询当前客户 邀约客户对应的服务顾问
                    def getSelectfwgwidSQL = eliteBean.chaxun_sql("select s.counselor_id as fwgw_id,s.staff_id as staff_id,s.DEFAULTROLEGROUP as rolegroup_id from objective o   LEFT JOIN CUSTOMER c on c.customer_guid=o.customer_guid  LEFT JOIN staff s on s.STAFF_ID=o.HANDLEBY_ID where 1=1 and s.Workstatus = 'ONLINE' and o.Map_Id='MY48ZX' and c.CUSTOMER_ID ='" + Inviter_Hstno + "'", "dataSource");
                    log.debug("查询当前名单的邀约客户绑定的服务顾问 SQL:" + getSelectfwgwidSQL + " 结果数量:" + getSelectfwgwidSQL.size());

                    if (getSelectfwgwidSQL.size() > 0) {
                        fwgw_id = getSelectfwgwidSQL.get(0).get("fwgw_id");//服务顾问核心系统id
                        staff_id = getSelectfwgwidSQL.get(0).get("staff_id");//分配人员staffid
                        rolegroup_id = getSelectfwgwidSQL.get(0).get("rolegroup_id");//分配人员组别
                        log.debug("查询当前名单的邀约客户绑定的服务顾问结果:" + fwgw_id + "&人员控制ID:" + staff_id + "&rolegroup_id:" + rolegroup_id);
                        if (fwgw_id != '' && fwgw_id != null) {
                            counselor_id = fwgw_id;
                            r_Control_Id = '0000';
                            //Rule_Id="0";//邀约
                            r_Staff_Id = staff_id;
                            r_Rolegroup_Id = rolegroup_id;
                            log.debug("当前名单服务顾问直接更换为邀约客户的服务顾问id:" + counselor_id + "&人员控制ID:" + r_Staff_Id + "&rolegroup_id:" + r_Rolegroup_Id);
                            //String assignLog = "开户自动下发-名单ID:" + Rec_Id + "&规则ID:" + Rule_Id + "邀约&人员控制ID:" + r_Control_Id + "&任务TaskGuid:" + EliteTask_Guid;
                        } else {
                            log.debug("当前名单服务顾问按均分逻辑派发！");
                        }
                    } else {
                        fwgw_id = "";
                    }

                }

                //邀约渠道注册客户 入库 进入未分配池
                if (register_id == "300050" && (Inviter_Hstno == '' || Inviter_Hstno == null)) {
                    newCustomerDeal(eliteBean, Rec_Id, Rule_Id, "0000", "", "", Inviter_Hstno, Customer_Guid, Phone, registerstatus);
                    long endTime = System.currentTimeMillis();
                    String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 5, Deal_Result = '邀约渠道注册客户 未匹配到邀约服务顾问 进入未分配池子-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                    eliteBean.update(updateCustSQL, "dataSource");

                } else if ((r_Rolegroup_Id == '' || r_Rolegroup_Id == null) && (r_Staff_Id == '' || r_Staff_Id == null)) {
                    //判断当前规则维护 组人是否有值 没有则进入未分配池 存在则按规则分配
                    //新客户入库 进入未分配池
                    newCustomerDeal(eliteBean, Rec_Id, Rule_Id, r_Control_Id, r_Rolegroup_Id, r_Staff_Id, Inviter_Hstno, Customer_Guid, Phone, registerstatus);
                    long endTime = System.currentTimeMillis();
                    String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 4, Deal_Result = '未匹配规则 进入未分配池子-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                    eliteBean.update(updateCustSQL, "dataSource");

                } else if (registerstatus == "5" || registerstatus == "2" || registerstatus == "3" || registerstatus == "4") {
                    //注册则判定绑定 2（注册） 5 （暂存申请） 3（暂存）4（审核中）
                    boolean CustchangerDeal2;
                    CustchangerDeal2 = dealBindCustTOStaff(Customerid, counselor_id);
                    log.debug("未开户234绑定结果-:" + CustchangerDeal2);

                    boolean newCustDeal;
                    //新增校验 绑定成功 再创建客户更新
                    if (CustchangerDeal2) {
                        newCustDeal = newCustomerDeal(eliteBean, Rec_Id, Rule_Id, r_Control_Id, r_Rolegroup_Id, r_Staff_Id, Inviter_Hstno, Customer_Guid, Phone, registerstatus);
                    } else {
                        newCustDeal = false;
                    }

                    //校验当名单绑定成功 且 创建也成功的时候
                    if (newCustDeal && CustchangerDeal2) {
                        // 更新规则下发记录
                        long endTime = System.currentTimeMillis();
                        String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 2, Deal_Result = '未开户客户新建下发成功:...绑定接口" + CustchangerDeal2 + ",当前任务华盛号：" + Customerid + "绑定服务顾问id：" + counselor_id + "涉及开户状态：" + registerstatus + " 系统已存在客户Customer_Guid：" + Customer_Guid + "-耗时:" + (endTime - startTime) + "'  Where Rec_Id = " + Rec_Id;

                        log.debug("下发成功-耗时:" + (endTime - startTime));
                        eliteBean.update(updateCustSQL, "dataSource");

                        //更新绑定标识
                        eliteBean.update("update Customer set distributionstatus=1 where Customer_Id='" + Customerid + "'", "dataSource");
                    } else {
                        long endTime = System.currentTimeMillis();
                        String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -1, Deal_Result = '未开户客户新建失败:...绑定接口异常" + CustchangerDeal2 + ",当前任务华盛号：" + Customerid + "已绑定服务顾问id：" + counselor_id + "涉及开户状态：" + registerstatus + " 系统已存在客户Customer_Guid：" + Customer_Guid + "-耗时:" + (endTime - startTime) + "'  Where Rec_Id = " + Rec_Id;
                        eliteBean.update(updateCustSQL, "dataSource");
                        log.warn("新建客户&任务失败-耗时:" + (endTime - startTime));
                        return 1;
                    }

                } else if (registerstatus == "1") {//属于已开户的客户（1开户）
                    boolean CustchangerDeal1;
                    CustchangerDeal1 = dealBindCustTOStaff(Customerid, counselor_id);
                    log.debug("已开户1绑定结果-:" + CustchangerDeal1);

                    boolean newCustDeal;
                    //新增校验 绑定成功 再创建客户更新
                    if (CustchangerDeal1) {
                        newCustDeal = newCustDeal = newCustomerDeal(eliteBean, Rec_Id, Rule_Id, r_Control_Id, r_Rolegroup_Id, r_Staff_Id, Inviter_Hstno, Customer_Guid, Phone, registerstatus);
                    } else {
                        newCustDeal = false;
                    }
                    //校验当名单绑定成功 且 创建也成功的时候
                    if (newCustDeal && CustchangerDeal1) {
                        // 更新规则下发记录
                        long endTime = System.currentTimeMillis();
                        String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 1, Deal_Result = '新建下发成功:...绑定接口" + CustchangerDeal1 + ",当前任务华盛号：" + Customerid + "绑定服务顾问id：" + counselor_id + "涉及开户状态：" + registerstatus + " 系统已存在客户Customer_Guid：" + Customer_Guid + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                        log.debug("下发成功-耗时:" + (endTime - startTime));
                        eliteBean.update(updateCustSQL, "dataSource");

                        //更新绑定标识
                        eliteBean.update("update Customer set distributionstatus=1 where Customer_Id='" + Customerid + "'", "dataSource");
                    } else {
                        long endTime = System.currentTimeMillis();
                        String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -1, Deal_Result = '新建下发开户客户更新失败...绑定接口异常" + CustchangerDeal1 + ",当前任务华盛号：" + Customerid + "已绑定服务顾问id：" + counselor_id + "涉及开户状态：" + registerstatus + " 系统已存在客户Customer_Guid：" + Customer_Guid + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                        eliteBean.update(updateCustSQL, "dataSource");
                        log.warn("新建客户&任务失败-耗时:" + (endTime - startTime));
                        return 1;
                    }

                } else if (registerstatus == "6") {//属于 已注销的客户

                    boolean newCustDeal = newCustomerDeal(eliteBean, Rec_Id, Rule_Id, r_Control_Id, "", "", Inviter_Hstno, Customer_Guid, Phone, registerstatus);
                    //校验当名单绑定成功 且 创建也成功的时候
                    if (newCustDeal) {
                        // 更新规则下发记录
                        long endTime = System.currentTimeMillis();
                        String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 4, Deal_Result = '开户状态涉及已注销 执行成功-当前任务华盛号：" + Customerid + "绑定服务顾问id：" + counselor_id + "涉及开户状态：" + registerstatus + " 系统已存在客户Customer_Guid：" + Customer_Guid + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                        log.debug("下发成功-耗时:" + (endTime - startTime));
                        eliteBean.update(updateCustSQL, "dataSource");

                        //更新绑定标识
                        eliteBean.update("update Customer set distributionstatus=1 where Customer_Id='" + Customerid + "'", "dataSource");
                    } else {
                        long endTime = System.currentTimeMillis();
                        String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -1, Deal_Result = '开户状态涉及已注销 执行失败-当前任务华盛号：" + Customerid + "已绑定服务顾问id：" + counselor_id + "涉及开户状态：" + registerstatus + " 系统已存在客户Customer_Guid：" + Customer_Guid + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                        eliteBean.update(updateCustSQL, "dataSource");
                        log.warn("新建客户&任务失败-耗时:" + (endTime - startTime));
                        return 1;
                    }

                } else {
                    long endTime = System.currentTimeMillis();
                    String updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -2, Deal_Result = '开户状态涉及其他 执行失败-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                    eliteBean.update(updateCustSQL, "dataSource");
                    log.warn("绑定服务顾问失败-耗时:" + (endTime - startTime));
                }

            } else {
                // 名单已经存在
                Map custCountMap = custCountList.get(0);
                long endTime = System.currentTimeMillis();

                //如邀约客户 则重新查询一下所属邀约人的服务顾问人组更新
                if (register_id == "300050" && Inviter_Hstno != '' && Inviter_Hstno != null) {
                    //查询当前客户 邀约客户对应的服务顾问
                    def staff_id, rolegroup_id = "";
                    def getSelectInviterSQL = eliteBean.chaxun_sql("select s.staff_id as staff_id,s.DEFAULTROLEGROUP as rolegroup_id from objective o   LEFT JOIN CUSTOMER c on c.customer_guid=o.customer_guid  LEFT JOIN staff s on s.STAFF_ID=o.HANDLEBY_ID where 1=1 and s.Workstatus = 'ONLINE' and o.Map_Id='MY48ZX' and c.CUSTOMER_ID ='" + Inviter_Hstno + "'", "dataSource");
                    log.debug("查询当前名单的邀约客户绑定的服务顾问 SQL结果数量:" + getSelectInviterSQL.size());
                    if (getSelectInviterSQL.size() > 0) {
                        staff_id = getSelectInviterSQL.get(0).get("staff_id");
                        rolegroup_id = getSelectInviterSQL.get(0).get("rolegroup_id");
                    }
                    log.debug("当前邀约客户所属服务顾问staff_id：" + staff_id + "	,rolegroup_id:" + rolegroup_id);

                    if (staff_id == null) {
                        staff_id = "";
                    }
                    if (rolegroup_id == null) {
                        rolegroup_id = "";
                    }

                    String[] data = new String[3];
                    data[0] = "update objective set HANDLEBY_ID='" + staff_id + "',HANDLEGROUP_ID='" + rolegroup_id + "' where 1=1 and MAP_ID='MY48ZX' and Customer_Guid = '" + custCountMap.get("Customer_Guid") + "' and IFNULL(LENGTH(HANDLEBY_ID),0)=0 and IFNULL(LENGTH(HANDLEGROUP_ID),0)=0";
                    data[1] = "update elitetask set HANDLEBY_ID='" + staff_id + "',HANDLEGROUP_ID='" + rolegroup_id + "' where 1=1 and MAP_ID='MY48ZX' and   Customer_Guid = '" + custCountMap.get("Customer_Guid") + "' and IFNULL(LENGTH(HANDLEBY_ID),0)=0 and IFNULL(LENGTH(HANDLEGROUP_ID),0)=0";
                    //检查  邀约客户入库 是否已经有记录
                    def getSelectAssign_HisSQL = eliteBean.chaxun_sql("select count(*) as count from Assign_His where 1=1 and Success_Guid='邀约客户入库' and  Customer_Guid='" + custCountMap.get("Customer_Guid") + "'", "dataSource");
                    log.debug("查询当前Assign_His 结果数量:" + getSelectAssign_HisSQL.get(0).get("count"));
                    if (getSelectAssign_HisSQL.get(0).get("count") == 0) {
                        data[2] = "Insert Into Assign_His (Assign_Guid, Customer_Guid, Objective_Guid, Oldhandlegroup_Id, Oldhandleby_Id, Newhandlegroup_Id, Newhandleby_Id, Assigngroup_Id, Assignby_Id, Assigndate, Success_Guid) Values (Uuid(), '" + custCountMap.get("Customer_Guid") + "', '', Null, Null, '" + rolegroup_id + "', '" + staff_id + "', 'SYSTEM', 'SELITE', Now(), '邀约客户入库')";
                    }
                    /*
                    String[] data=new String[2];
                    data[0] = "update objective set HANDLEBY_ID='" + staff_id + "',HANDLEGROUP_ID='" + rolegroup_id + "' where 1=1 and MAP_ID='MY48ZX' and Customer_Guid = '" + custCountMap.get("Customer_Guid") + "'";
                    data[1] = "update elitetask set HANDLEBY_ID='" + staff_id + "',HANDLEGROUP_ID='" + rolegroup_id + "' where 1=1 and MAP_ID='MY48ZX' and   Customer_Guid = '" + custCountMap.get("Customer_Guid") + "'";
                    */
                    log.debug("更新邀约客户的服务顾问处理SQL:" + data.toString());
                    int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                    log.debug("更新邀约客户的服务顾问处理SQL结果:" + dataresult.toString());
                }

                //查询当前已存在客户是否属未开户，如是则查询出当前处理人 再变更绑定
                def khzt, fwgwid = "";
                String updateCustSQL = "";
                List custstaffList = eliteBean.chaxun_sql("select c.registerstatus as khzt,s.counselor_id as fwgwid from customer c LEFT JOIN objective o on c.customer_guid=o.customer_guid LEFT JOIN staff s on s.staff_id=o.HANDLEBY_ID where  o.MAP_ID='MY48ZX' and  c.Customer_Guid = '" + custCountMap.get("Customer_Guid") + "' and c.Customer_Id = '" + Customerid + "'", "dataSource");
                if (custstaffList.size() > 0) {
                    fwgwid = custstaffList.get(0).get("fwgwid");//服务顾问id
                    khzt = custstaffList.get(0).get("khzt");//开户状态
                }
                log.debug("当前服务顾问id：" + fwgwid + "	,开户状态：" + khzt);
                if (fwgwid != "" && fwgwid != null && distributionstatus != 1 && registerstatus != "6") {
                    //判断当前客户注册渠道是否是邀约渠道，如是 则查询中台系统所属人 变更
                    /*
                    if(register_id=="300050"){
                        //查询当前客户 邀约客户对应的服务顾问
                        def getSelectfwgwidSQL = eliteBean.chaxun_sql("select s.counselor_id as fwgw_id from objective o   LEFT JOIN CUSTOMER c on c.customer_guid=o.customer_guid  LEFT JOIN staff s on s.STAFF_ID=o.HANDLEBY_ID where 1=1 and s.Workstatus = 'ONLINE' and o.Map_Id='MY48ZX' and c.CUSTOMER_ID ='" + Inviter_Hstno + "'", "dataSource");
                        log.debug("查询当前名单的邀约客户绑定的服务顾问 SQL:" + getSelectfwgwidSQL + " 结果数量:" + getSelectfwgwidSQL.size());
                        if(getSelectfwgwidSQL.size() > 0) {
                            fwgwid = getSelectfwgwidSQL.get(0).get("fwgw_id");//服务顾问核心系统id
                        }
                        log.debug("当前邀约客户所属服务顾问id：" + fwgwid);
                    }
                    */
                    //由未开户转变成已开户 则实施绑定
                    boolean CustchangerDeal = dealBindCustTOStaff(Customerid, fwgwid);
                    if (CustchangerDeal) {
                        //邀约客户入库 检查绑定成功 后则更新 实际的下发实际+时间的分配时间
                        String[] data = new String[3];
                        data[0] = "update objective set distributiontime=now() where 1=1 and MAP_ID='MY48ZX' and Customer_Guid = '" + custCountMap.get("Customer_Guid") + "'";
                        data[1] = "update elitetask set createddate=now() where 1=1 and MAP_ID='MY48ZX' and   Customer_Guid = '" + custCountMap.get("Customer_Guid") + "'";
                        //更新绑定标识
                        data[2] = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 3, Deal_Result = '当前开户客户,由未绑定转化成功...绑定接口" + CustchangerDeal + ",当前任务华盛号：" + Customerid + "绑定服务顾问id：" + fwgwid + "涉及开户状态：" + khzt + " 系统已存在客户Customer_Guid：" + custCountMap.get("Customer_Guid") + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                        log.debug("更新邀约客户的分配时间处理SQL:" + data.toString());
                        int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                        log.debug("更新邀约客户的分配时间处理SQL结果:" + dataresult.toString());

                    } else {
                        updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -3, Deal_Result = '当前开户客户,由未绑定转化失败（可能涉及注册已绑定！）...绑定接口" + CustchangerDeal + ",当前任务华盛号：" + Customerid + "绑定服务顾问id：" + fwgwid + "涉及开户状态：" + khzt + " 系统已存在客户Customer_Guid：" + custCountMap.get("Customer_Guid") + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                    }
                } else if (register_id == "300050" && Inviter_Hstno != '' && Inviter_Hstno != null) {
                    updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 3, Deal_Result = '当前开户客户的华盛号系统已经存在...当前任务华盛号：" + Customerid + "绑定服务顾问id：" + fwgwid + "涉及开户状态：" + khzt + " 系统已存在客户Customer_Guid：" + custCountMap.get("Customer_Guid") + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                } else if (registerstatus == "6") {
                    //已注销客户数据入库  优先记入 分配his  之后单方面解除绑定更新
                    String[] data = new String[3];
                    data[0] = "Insert Into Assign_His (Assign_Guid, Customer_Guid, Objective_Guid, Oldhandlegroup_Id, Oldhandleby_Id, Newhandlegroup_Id, Newhandleby_Id, Assigngroup_Id, Assignby_Id, Assigndate, Success_Guid) select Uuid(), Customer_Guid, '', HANDLEGROUP_ID, HANDLEBY_ID, Null, Null, 'SYSTEM', 'SELITE', Now(), '客户开户状态注销更新' from objective where 1=1 and MAP_ID='MY48ZX' and Customer_Guid = '" + custCountMap.get("Customer_Guid") + "'";
                    data[1] = "update objective set HANDLEBY_ID='',HANDLEGROUP_ID='' where 1=1 and MAP_ID='MY48ZX' and Customer_Guid = '" + custCountMap.get("Customer_Guid") + "'";
                    data[2] = "update elitetask set HANDLEBY_ID='',HANDLEGROUP_ID='' where 1=1 and MAP_ID='MY48ZX' and Customer_Guid = '" + custCountMap.get("Customer_Guid") + "'";
                    log.debug("已经存在名单，触发已注销状态数据入库SQL:" + data.toString());
                    int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                    log.debug("已经存在名单，触发已注销状态数据入库SQL结果:" + dataresult.toString());

                    updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = 4, Deal_Result = '当前开户客户的华盛号系统已经存在...已注销执行成功-当前任务华盛号：" + Customerid + "绑定服务顾问id：" + fwgwid + "涉及开户状态：" + khzt + " 系统已存在客户Customer_Guid：" + custCountMap.get("Customer_Guid") + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                } else {
                    updateCustSQL = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = -3, Deal_Result = '当前开户客户的华盛号系统已经存在...当前任务华盛号：" + Customerid + "涉及服务顾问id：" + fwgwid + "涉及开户状态：" + khzt + " 系统已存在客户Customer_Guid：" + custCountMap.get("Customer_Guid") + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = " + Rec_Id;
                }

                eliteBean.update(updateCustSQL, "dataSource");

                //对手机号码 做脱敏处理
                String Phone_enc = DecryptUtil.encrypt(Phone);

                // TODO 待补充已存在名单的下发逻辑
                //注册未开户客户后续同步信息更新 registerstatus
                String q_SetSQL = "update Customer c LEFT JOIN Account_Information a ON c.Customer_Id = a.customerid " +
                        "set c.Customername=case when a.Customername is null or a.Customername='' then c.Customername else a.Customername end," +
                        "c.Gender=case when a.Gender is null or a.Gender='' then c.Gender else a.Gender end," +
                        "c.Mobile='***'," +
                        "c.Mobile_enc=case when (a.Phone is null or a.Phone='') and a.registerstatus=6 then c.Mobile_enc else '" + Phone_enc + "' end," +
                        "c.Sq_2=case when a.Accounttype is null or a.Accounttype='' then c.Sq_2 else a.Accounttype end," +
                        "c.Stringfield3=case when a.tradepermission is null or a.tradepermission='' then c.Stringfield3 else a.tradepermission end," +
                        "c.Stringfield13=case when a.Register is null or a.Register='' then c.Stringfield13 else a.Register end," +
                        "c.sq_9=case when a.register_id is null or a.register_id='' then c.sq_9 else a.register_id end," +
                        "c.Stringfield7=case when a.Registertime is null or a.Registertime='' then c.Stringfield7 else a.Registertime end," +
                        "c.Stringfield8=case when a.Opentime is null or a.Opentime='' then c.Stringfield8 else a.Opentime end," +
                        "c.Sq_5=case when a.Inviter_Hstno is null or a.Inviter_Hstno='' then c.Sq_5 else a.Inviter_Hstno end," +
                        "c.Sq_6=case when a.Inviter_Name is null or a.Inviter_Name='' then c.Sq_6 else a.Inviter_Name end," +
                        "c.Sq_7=case when a.Inviter_Type is null or a.Inviter_Type='' then c.Sq_7 else a.Inviter_Type end," +
                        "c.registerstatus=case when a.registerstatus=6 then 6 when c.registerstatus=1 then 1 when a.registerstatus is null or a.registerstatus='' then c.registerstatus else a.registerstatus end," +
                        "c.stashtime=case when c.stashtime is null then a.stashtime else c.stashtime end," +
                        "c.audittime=case when c.audittime is null then a.audittime else c.audittime end," +
                        "c.MODIFIEDBY='SELITE'," +
                        "c.MODIFIEDDATE=Now()" +
                        "where c.Customer_Id='" + Customerid + "' and a.customerid='" + Customerid + "' and a.Batch_Guid = '" + content + "'";
                eliteBean.update(q_SetSQL, "dataSource");

                log.debug("当前开户客户的华盛号系统已经存在...当前任务华盛号：" + Customerid + "涉及服务顾问id：" + fwgwid + "涉及开户状态：" + khzt + " 系统已存在客户Customer_Guid：" + custCountMap.get("Customer_Guid") + "-耗时:" + (endTime - startTime));

            }

            //给邀约客户 累计邀请客户数【】 sq_12默认初始值是从0开始
            if (Inviter_Hstno != '' && Inviter_Hstno != null) {
                eliteBean.update("Update customer Set sq_12 = sq_12+1 Where customer_id ='" + Inviter_Hstno + "'", "dataSource");
            }

            //活动复查绑定
            boolean newActivityDeal = dealActivityVerify(Customerid, register_id);
            log.debug("活动复查绑定情况:" + newActivityDeal);

        }
        return 1;
    }

    /**
     * 规则下发数据初始化
     * @param eliteBean
     * @param Rule_Id
     * @return
     */
    public static boolean ruleAssignInit(EliteBean eliteBean, String Rule_Id, String weight, String allocation_method, String Rolegroup, String Staff_Id) {
        boolean reFlag = true;

        //新增判断坐席B岗接任时间的逻辑截止状态、及离职人员默认不分配
        //A.-如果有离职人员 则直接关闭其分配状态-- 是否开启自动分配 0开启 1关闭
        String updatestaffstate1SQL = "update staff" +
                " set auto_allocation=1 " +
                " Where auto_allocation=0 " +
                "   And workstatus!='ONLINE'";
        eliteBean.update(updatestaffstate1SQL, "dataSource");

        //B.-如果有B岗角色接任时间到期 则更新企状态为自动开启分配 +清空时间维护
        String updatestaffstate2SQL = "update staff" +
                " set auto_allocation=0,starttime=null,endtime=null " +
                " Where auto_allocation=1 " +
                " 	And starttime <now()" +
                "   And endtime<now()";
        eliteBean.update(updatestaffstate2SQL, "dataSource");

        //如按组分配  初始 删除不在范围内的组别
        if (allocation_method == "按组分配") {
            String updatestaffstate3SQL = "delete from Hst_Rule_Issue_Control " +
                    " where Rule_Id = '" + Rule_Id + "' And Assign_Date = Date_Format(Now(), '%Y-%m-%d') " +
                    " and  Find_In_Set(rolegroup_id,'" + Rolegroup + "') =0 ";
            eliteBean.update(updatestaffstate3SQL, "dataSource");
        }

        //如按人员分配  初始 删除不在范围内的同学
        if (allocation_method == "按人员分配") {
            String updatestaffstate4SQL = "delete from Hst_Rule_Issue_Control where " +
                    " Rule_Id ='" + Rule_Id + "' And Assign_Date = Date_Format(Now(), '%Y-%m-%d') " +
                    " and Find_In_Set(staff_id,'" + Staff_Id + "')= 0";
            eliteBean.update(updatestaffstate4SQL, "dataSource");
        }

        //判断分配类型 allocation_method 类型标识 按组分配 按人员分配
        //weight 权重{"weight_json":[{"qzId":"IB0001","qzName":"客服","proportion":"30"},{"qzId":"TEAM01","qzName":"服务顾问","proportion":"50"},{"qzId":"WM92BU","qzName":"非主流一组","proportion":"20"}]}

        JSONObject inObject = new JSONObject(weight);
        //log.debug("inObject=>"+inObject);
        String weight_json = GetJV(inObject, "weight_json");
        //log.debug("weight_json=>"+weight_json);

        JSONArray arrJsonArray = new JSONArray(weight_json);
        int arrInt = arrJsonArray.length();
        log.debug("接入List权重数量:" + arrInt);

        for (int i = 0; i < arrInt; i++) {
            JSONObject arrJson = arrJsonArray.getJSONObject(i);
            //获取信息
            String qzId = GetJV(arrJson, "qzId");
            //String qzName = GetJV(arrJson, "qzName");
            String proportion = GetJV(arrJson, "proportion");
            log.debug("接入qzId:" + qzId);
            //log.debug("接入qzName:" + qzName);
            log.debug("接入proportion:" + proportion);

            //如 默认0  则按 1:1的模式均分
            if (proportion == "0") {
                proportion = 1;
            }

            if (allocation_method == "按组分配") {

                // 1- 获取当前组下的均值 Assign_Num
                //def selectassignnumSQL = "select case when count(*)=0 then 0 else  round(sum(assign_num)/count(*)) end as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + " and rolegroup_id = '" + qzId + "'  And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
                def selectassignnumSQL = "select ifnull(case when sum(assign_num)=0 then 0 else  round(sum(assign_num)/count(*)) end,0) as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + " and rolegroup_id = '" + qzId + "'  And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
                def selectassignnumresult = eliteBean.chaxun_sql(selectassignnumSQL, "dataSource");
                def assignnum = 0;
                if (selectassignnumresult.size() > 0) {
                    assignnum = selectassignnumresult.get(0).get("assignnum");
                }
                log.debug("assignnum:    " + assignnum);

                // 2- 将不存在当前规则 组下的人统一写入
                String insertStaffSQL = "Insert Into Hst_Rule_Issue_Control" +
                        "  (Rule_Id,rolegroup_id,Staff_Id,Assign_Date,proportion,Assign_Num,assign_yynum, Last_Check_Time)" +
                        "  Select DISTINCT " + Rule_Id + ",r.rolegroup_id, s.Staff_Id, Date_Format(Now(), '%Y-%m-%d')," + proportion + ",'" + assignnum + "', 0, Now()" +
                        "    From rolegroup r" +
                        "    left join staffrolegroup srg on r.ROLEGROUP_ID=srg.ROLEGROUP_ID" +
                        "    left join staff s on s.staff_id=srg.staff_id" +
                        "   where 1=1  and s.staff_id is not null" +
                        "   			and r.ROLEGROUP_ID='" + qzId + "'" +
                        "     And s.Staff_Id Not In (Select Staff_Id" +
                        "                            From Hst_Rule_Issue_Control" +
                        "                           Where Rule_Id = " + Rule_Id + "" +
                        "                           And rolegroup_id = '" + qzId + "'" +
                        "                           And Assign_Date = Date_Format(Now(), '%Y-%m-%d'))";
                log.debug("insertStaffSQL:    " + insertStaffSQL);

                int newStaffNum = eliteBean.update(insertStaffSQL, "dataSource");

                // 3-将不需要不满足下发的坐席删除，防止中途规则配置的人或组删除
                String deleteStaffSQL = "Delete From Hst_Rule_Issue_Control" +
                        " Where Staff_Id Not In" +
                        "       (Select s.Staff_Id" +
                        "    		From rolegroup r" +
                        "    		left join staffrolegroup srg on r.ROLEGROUP_ID=srg.ROLEGROUP_ID" +
                        "   		left join staff s on s.staff_id=srg.staff_id" +
                        "   		where 1=1  and s.staff_id is not null" +
                        "   					and r.ROLEGROUP_ID='" + qzId + "'" +
                        "   					And ((s.auto_allocation = 0) " +
                        " 						or (s.auto_allocation = 1 And s.starttime>now() And s.endtime>now() And s.starttime is not null And s.endtime is not null)" +
                        " 						or (s.auto_allocation = 1 And s.starttime<now() And s.endtime<now() And s.starttime is not null And s.endtime is not null))" +
                        "   And s.Workstatus = 'ONLINE')" +
                        "   And Rule_Id = " + Rule_Id + "" +
                        "   And rolegroup_id = '" + qzId + "'" +
                        "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
                log.debug("deleteStaffSQL:    " + deleteStaffSQL);

                eliteBean.update(deleteStaffSQL, "dataSource");

            } else if (allocation_method == "按人员分配") {
                // 1- 获取当前组下的均值 Assign_Num  按比例计算 则先拿均值 累计数除以比例 再得出均值 乘以当前的比例 得出当前分配的均值
                //def selectassignnumSQL = "select case when count(*)=0 then 0 else  round(sum(round(assign_num+1/proportion,2))/count(*))*" + proportion + " end as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + " And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
                def selectassignnumSQL = "select ifnull(case when sum(assign_num)=0 then 0 else  round(sum(round(assign_num/proportion,2))/count(*))*" + proportion + " end,0) as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + " And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";

                def selectassignnumresult = eliteBean.chaxun_sql(selectassignnumSQL, "dataSource");
                def assignnum = 0;
                if (selectassignnumresult.size() > 0) {
                    assignnum = selectassignnumresult.get(0).get("assignnum");
                }
                log.debug("assignnum:    " + assignnum);

                // 2- 将不存在当前规则 的有效人 写入
                String insertStaffSQL = "Insert Into Hst_Rule_Issue_Control" +
                        "  (Rule_Id,rolegroup_id,Staff_Id,Assign_Date,proportion,Assign_Num,assign_yynum, Last_Check_Time)" +
                        "  Select " + Rule_Id + ",s.DEFAULTROLEGROUP, s.Staff_Id, Date_Format(Now(), '%Y-%m-%d')," + proportion + ",'" + assignnum + "', 0, Now()" +
                        "    From staff s" +
                        "   where 1=1  and s.staff_id ='" + qzId + "'" +
                        "   And s.Staff_Id Not In (Select Staff_Id" +
                        "                            From Hst_Rule_Issue_Control" +
                        "                           Where Rule_Id = " + Rule_Id + "" +
                        "                           And staff_id = '" + qzId + "'" +
                        "                           And Assign_Date = Date_Format(Now(), '%Y-%m-%d'))";
                log.debug("insertStaffSQL:    " + insertStaffSQL);

                int newStaffNum = eliteBean.update(insertStaffSQL, "dataSource");

                // 3-将不需要不满足下发的坐席删除，防止中途规则配置的人或组删除
                String deleteStaffSQL = "Delete From Hst_Rule_Issue_Control" +
                        " Where Staff_Id Not In" +
                        "       (Select Staff_Id" +
                        "          From Staff" +
                        "         Where staff_id ='" + qzId + "'" +
                        "   And ((auto_allocation = 0) " +
                        " 	or (auto_allocation = 1 And starttime>now() And endtime>now() And starttime is not null And endtime is not null)" +
                        " 	or (auto_allocation = 1 And starttime<now() And endtime<now() And starttime is not null And endtime is not null))" +
                        "   And Workstatus = 'ONLINE')" +
                        "   And Rule_Id = " + Rule_Id + "" +
                        "   And staff_id ='" + qzId + "'" +
                        "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";

                log.debug("deleteStaffSQL:    " + deleteStaffSQL);

                eliteBean.update(deleteStaffSQL, "dataSource");

            }
        }

/*
		// 初始化（1~4）下发记录表（这里默认按每天清零）
		// 1-查找当前规则配置的坐席
		String ruleStaffSQL = "Select Case" +
				"         When R1.Staff_Id Is Null Or R1.Staff_Id = '' Then" +
				"          R2.Staff_Id" +
				"         Else" +
				"          R1.Staff_Id" +
				"       End As ruleStaff" +
				"  From Hst_Rule_Issue R1" +
				"  Left Join (Select R4.Rule_Id, Group_Concat(Distinct R3.Staff_Id) As Staff_Id" +
				"               From Rolegroup R1" +
				"               Left Join Staffrolegroup R2" +
				"                 On R1.Rolegroup_Id = R2.Rolegroup_Id" +
				"               Left Join Staff R3" +
				"                 On R2.Staff_Id = R3.Staff_Id" +
				"               Left Join Hst_Rule_Issue R4" +
				"                 On Find_In_Set(R1.Rolegroup_Id, R4.Rolegroup) > 0" +
				"              Where R1.Status = 1" +
				"                And ((R3.auto_allocation = 0) " +
				" 				or (R3.auto_allocation = 1 And R3.starttime>now() And R3.endtime>now() And R3.starttime is not null And R3.endtime is not null)" +
				" 				or (R3.auto_allocation = 1 And R3.starttime<now() And R3.endtime<now() And R3.starttime is not null And R3.endtime is not null))" +
				"                And R3.Workstatus = 'ONLINE'" +
				"                And R4.Rule_Id = " + Rule_Id + ") R2" +
				"    On R1.Rule_Id = R2.Rule_Id" +
				"   And (R1.Staff_Id Is Null Or R1.Staff_Id = '')" +
				" Where R1.Rule_Id = " + Rule_Id + "";

		List ruleStaffList = eliteBean.chaxun_sql(ruleStaffSQL, "dataSource");

		Map ruleStaffMap = ruleStaffList.get(0);
		log.debug("ruleStaffMap:    "+ruleStaffMap);
		String ruleStaff = ruleStaffMap.get("ruleStaff");
		log.debug("ruleStaff:    "+ruleStaff);
		//处理Assign_Num
		def selectassignnumSQL = "select case when count(*)=0 then 0 else  round(sum(assign_num)/count(*)) end as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + "  And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
		def selectassignnumresult = eliteBean.chaxun_sql(selectassignnumSQL, "dataSource");
		def assignnum =0;
		if (selectassignnumresult.size() > 0) {
			assignnum = selectassignnumresult.get(0).get("assignnum");
		}
		log.debug("assignnum:    "+assignnum);

		// 2-将不在下发规则表中不存在的坐席补充，防止中途规则配置的人或组修改添加
		String insertStaffSQL = "Insert Into Hst_Rule_Issue_Control" +
				"  (Rule_Id, Staff_Id, Assign_Date, Assign_Num,assign_yynum, Last_Check_Time)" +
				"  Select " + Rule_Id + ", Staff_Id, Date_Format(Now(), '%Y-%m-%d'), '" + assignnum + "', 0, Now()" +
				"    From Staff" +
				"   Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
				"     And Staff_Id Not In (Select Staff_Id" +
				"                            From Hst_Rule_Issue_Control" +
				"                           Where Rule_Id = " + Rule_Id + "" +
				"                             And Assign_Date = Date_Format(Now(), '%Y-%m-%d'))";
		int newStaffNum = eliteBean.update(insertStaffSQL, "dataSource");

		// 3-将不需要不满足下发的坐席删除，防止中途规则配置的人或组删除
		String deleteStaffSQL = "Delete From Hst_Rule_Issue_Control" +
				" Where Staff_Id Not In" +
				"       (Select Staff_Id" +
				"          From Staff" +
				"         Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
				"   And ((auto_allocation = 0) " +
				" 	or (auto_allocation = 1 And starttime>now() And endtime>now() And starttime is not null And endtime is not null)" +
				" 	or (auto_allocation = 1 And starttime<now() And endtime<now() And starttime is not null And endtime is not null))" +
				"   And Workstatus = 'ONLINE')"+
				"   And Rule_Id = " + Rule_Id + ""+
				"   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
		eliteBean.update(deleteStaffSQL, "dataSource");
*/
        // 4-如果有新加的人员将规则坐席已下发数量全部归零
        /*
        if (newStaffNum > 0) {
            String updateAssignNum = "Update Hst_Rule_Issue_Control" +
                    "   Set Assign_Num = 0,assign_yynum = 0, Last_Check_Time = Now()" +
                    " Where Rule_Id = " + Rule_Id + "" +
                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
            eliteBean.update(updateAssignNum, "dataSource");
        }
        */


        return reFlag;
    }

    /**
     * 新客户入库
     * @param eliteBean
     * @param Rule_Id
     * @return
     */
    public static boolean newCustomerDeal(EliteBean eliteBean, String Rec_Id, String Rule_Id, String r_Control_Id, String r_Rolegroup_Id, String r_Staff_Id, String Inviter_Hstno, String customerguid, String Phone, String registerstatus) {
        boolean reFlag = true;

        try {
            // 生成相关ID
            String Temp_Guid = KHUtil.getRandomString(31).toUpperCase();
            String Customer_Guid, Objective_Guid, EliteTask_Guid;
            log.debug("customerguid:    " + customerguid);

            if (customerguid != '' && customerguid != null) {
                Customer_Guid = customerguid;
            } else {
                Customer_Guid = "CUST_" + Temp_Guid;
            }
            log.debug("Customer_Guid:    " + Customer_Guid);
            Objective_Guid = "OBJE_" + Temp_Guid;
            EliteTask_Guid = "TASK_" + Temp_Guid;

            //对手机号码 做脱敏处理
            String Phone_enc = DecryptUtil.encrypt(Phone);

            String[] custTaskDealSQL = new String[6];
            // 插入Customer表
            if (customerguid != '' && customerguid != null) {
                custTaskDealSQL[0] = "update Customer c,Account_Information a set c.Customername=a.Customername,c.Gender=a.Gender,c.Mobile='***',c.Mobile_enc='" + Phone_enc + "',c.Sq_2=a.Accounttype,c.Stringfield3=a.tradepermission,c.Stringfield13=case when a.Register is null or a.Register='' then c.Stringfield13 else a.Register end,c.sq_9=a.register_id,c.Stringfield7=a.Registertime,c.Stringfield8=a.Opentime,c.Sq_5=a.Inviter_Hstno,c.Sq_6=a.Inviter_Name,c.Sq_7=a.Inviter_Type,c.registerstatus=a.registerstatus,c.MODIFIEDBY='SELITE',c.MODIFIEDDATE=Now()  where c.Customer_Guid='" + Customer_Guid + "' and a.Rec_Id = '" + Rec_Id + "'";
            } else {
                custTaskDealSQL[0] = "Insert Into Customer" +
                        "  (Customer_Guid," +
                        "   Customer_Id," +
                        "   Customername," +
                        "   Gender," +
                        "   Mobile," +
                        "   Mobile_enc," +
                        "   Sq_2," +
                        "   Stringfield3," +
                        "   Stringfield13," +
                        "   sq_9," +
                        "   Stringfield7," +
                        "   Stringfield8," +
                        "   Stringfield9," +
                        "   Sq_5," +
                        "   Sq_6," +
                        "   Sq_7," +
                        "   registerstatus," +
                        "   stashtime," +
                        "   audittime," +
                        "   Createdby," +
                        "   Createddate)" +
                        "  Select '" + Customer_Guid + "'," +
                        "         Customerid," +
                        "         Customername," +
                        "         Gender," +
                        "         '***'," +
                        "         '" + Phone_enc + "'," +
                        "         Accounttype," +
                        "         tradepermission," +
                        "         Register," +
                        "         register_id," +
                        "         Registertime," +
                        "         Opentime," +
                        "         Customerid," +
                        "         Inviter_Hstno," +
                        "         Inviter_Name," +
                        "         Inviter_Type," +
                        "         registerstatus," +
                        "         stashtime," +
                        "         audittime," +
                        "         'SELITE'," +
                        "         Now()" +
                        "    From Account_Information" +
                        "   Where Rec_Id = '" + Rec_Id + "'";
            }

            // 插入Objective表
            custTaskDealSQL[1] = "Insert Into Objective" +
                    "  (Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Priority_Id," +
                    "   Expireddate," +
                    "   Customer_Guid," +
                    "   Objectivestatus," +
                    "   Iscontact," +
                    "   Trytimes," +
                    "   Successfulcontacttimes," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Obstatus," +
                    "   Failure_Attempt," +
                    "   Contact_Customer_Guid," +
                    "   Passflag," +
                    "   Lastassigndate," +
                    "   Failstatus," +
                    "   Successstatus," +
                    "   Owner," +
                    "   Workorderframe_Id," +
                    "   Category," +
                    "   Forecastdate," +
                    "   Workorderid," +
                    "   Workordertype1," +
                    "   Workordertype2," +
                    "   Workordertype3," +
                    "   Workordertype4," +
                    "   Objectivesubstatus," +
                    "   Map_Id," +
                    "   Curstep_Id_Map," +
                    "   Max_Attempt," +
                    "   Nocontacttry," +
                    "   Allocation_Pool," +
                    "   Appointment," +
                    "   distributiontime," +
                    "   distributionnumber)" +
                    "Values" +
                    "  ('" + Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'NORMAL'," +
                    "   Date_Add(Now(), Interval 1 Day)," +
                    "   '" + Customer_Guid + "'," +
                    "   'OPEN'," +
                    "   0," +
                    "   0," +
                    "   0," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   'OPEN'," +
                    "   999," +
                    "   ''," +
                    "   0," +
                    "   Null," +
                    "   '0'," +
                    "   '0'," +
                    "   ''," +
                    "   'MY48ZX'," +
                    "   'CASE'," +
                    "   '2021-04-25 17:59:35'," +
                    "   Concat('HS', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
                    "   'QL800E'," +
                    "   'O7JIUV'," +
                    "   ''," +
                    "   ''," +
                    "   ''," +
                    "   'MY48ZX'," +
                    "   'ONA0KD'," +
                    "   0," +
                    "   0," +
                    "   0," +
                    "   0," +
                    "   Now()," +
                    "   1)";

            // 插入EliteTask表
            custTaskDealSQL[2] = "Insert Into Elitetask" +
                    "  (Elitetask_Guid," +
                    "   Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Expectstarttime," +
                    "   Expectendtime," +
                    "   Obstatus," +
                    "   Recordstatus," +
                    "   Attempt," +
                    "   Max_Attempt," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Failure_Attempt," +
                    "   Comments," +
                    "   Customer_Guid," +
                    "   Localtrycount," +
                    "   Lastassigndate," +
                    "   Workorderframe_Id," +
                    "   Curstepstatus," +
                    "   Curstep_Id," +
                    "   Stepforecastdate," +
                    "   Curstep_Id_Map," +
                    "   Map_Id," +
                    "   Objectivesubstatus," +
                    "   Elitetaskstatus," +
                    "   Obflag,Maintaskstep_Id_Map)" +
                    "Values" +
                    "  ('" + EliteTask_Guid + "'," +
                    "   '" + Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   Now()," +
                    "   Date_Add(Now(), Interval 3 Day)," +
                    "   'OPEN'," +
                    "   0," +
                    "   1," +
                    "   999," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   999," +
                    "   ''," +
                    "   '" + Customer_Guid + "'," +
                    "   0," +
                    "   Now()," +
                    "   ''," +
                    "   'OPEN'," +
                    "   'ONA0KD'," +
                    "   Now()," +
                    "   'ONA0KD'," +
                    "   'MY48ZX'," +
                    "   ''," +
                    "   'OPEN'," +
                    "   1,'ONA0KD')";

            // 插入Assign_His表
            String assignLog = "开户自动下发-名单ID:" + Rec_Id + "&规则ID:" + Rule_Id + "&人员控制ID:" + r_Control_Id + "&任务TaskGuid:" + EliteTask_Guid;
            log.debug(assignLog);
            //判断是否需要入池分配
            log.debug(Inviter_Hstno + ":===Inviter_Hstno+长度" + Inviter_Hstno.length())
            if ((r_Rolegroup_Id == '' || r_Rolegroup_Id == null) && (r_Staff_Id == '' || r_Staff_Id == null)) {
                log.debug("仅入未分配池库！");
            } else if ((r_Rolegroup_Id != '' || r_Rolegroup_Id != null) && (r_Staff_Id != '' || r_Staff_Id != null) && (Inviter_Hstno != null && Inviter_Hstno.length() > 0)) {
                log.debug("仅入属客户邀约！");
                custTaskDealSQL[3] = "Insert Into Assign_His (Assign_Guid, Customer_Guid, Objective_Guid, Oldhandlegroup_Id, Oldhandleby_Id, Newhandlegroup_Id, Newhandleby_Id, Assigngroup_Id, Assignby_Id, Assigndate, Success_Guid) Values (Uuid(), '" + Customer_Guid + "', '" + Objective_Guid + "', Null, Null, '" + r_Rolegroup_Id + "', '" + r_Staff_Id + "', 'SYSTEM', 'SELITE', Now(), '" + assignLog + "')";
            } else if (registerstatus == "6") {
                log.debug("已注销客户入库！");
                custTaskDealSQL[3] = "Insert Into Assign_His (Assign_Guid, Customer_Guid, Objective_Guid, Oldhandlegroup_Id, Oldhandleby_Id, Newhandlegroup_Id, Newhandleby_Id, Assigngroup_Id, Assignby_Id, Assigndate, Success_Guid) Values (Uuid(), '" + Customer_Guid + "', '" + Objective_Guid + "', Null, Null, '" + r_Rolegroup_Id + "', '" + r_Staff_Id + "', 'SYSTEM', 'SELITE', Now(), '客户开户状态注销更新')";
            } else {
                custTaskDealSQL[3] = "Insert Into Assign_His (Assign_Guid, Customer_Guid, Objective_Guid, Oldhandlegroup_Id, Oldhandleby_Id, Newhandlegroup_Id, Newhandleby_Id, Assigngroup_Id, Assignby_Id, Assigndate, Success_Guid) Values (Uuid(), '" + Customer_Guid + "', '" + Objective_Guid + "', Null, Null, '" + r_Rolegroup_Id + "', '" + r_Staff_Id + "', 'SYSTEM', 'SELITE', Now(), '" + assignLog + "')";

                // 更新下发中间表
                //如存在邀约华盛号，则说明当前名单属于邀约类型 不计入均分策略
                if (Inviter_Hstno != '' && Inviter_Hstno != null) {
                    custTaskDealSQL[4] = "Update Hst_Rule_Issue_Control Set assign_yynum = assign_yynum + 1, Last_Check_Time = Now() Where Rec_Id = " + r_Control_Id;
                    custTaskDealSQL[5] = "Update Hst_Rule_Issue Set assign_yynum = Ifnull(assign_yynum, 0) + 1, Today_Assign_Num = Case When Today_Assign_Date = Date_Format(Now(), '%Y-%m-%d') Then Ifnull(Today_Assign_Num, 0) + 1 Else 1 End, Today_Assign_Date " +
                            "= Case When Today_Assign_Date = Date_Format(Now(), '%Y-%m-%d') Then Today_Assign_Date Else Date_Format(Now(), '%Y-%m-%d') End Where Rule_Id = " + Rule_Id + "";
                } else {
                    custTaskDealSQL[4] = "Update Hst_Rule_Issue_Control Set Assign_Num = Assign_Num + 1, Last_Check_Time = Now() Where Rec_Id = " + r_Control_Id;
                    custTaskDealSQL[5] = "Update Hst_Rule_Issue Set Assign_Num = Ifnull(Assign_Num, 0) + 1, Today_Assign_Num = Case When Today_Assign_Date = Date_Format(Now(), '%Y-%m-%d') Then Ifnull(Today_Assign_Num, 0) + 1 Else 1 End, Today_Assign_Date " +
                            "= Case When Today_Assign_Date = Date_Format(Now(), '%Y-%m-%d') Then Today_Assign_Date Else Date_Format(Now(), '%Y-%m-%d') End Where Rule_Id = " + Rule_Id + "";
                }
            }
            log.debug("新客户入库批量处理SQL：" + custTaskDealSQL);
            int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
            log.debug("新客户入库批量处理SQL返回结果：" + batchSQLResult.toString());

        } catch (Exception e) {
            log.error("新客户入库异常!", e);
            reFlag = false;
        }

        return reFlag;
    }

    /**
     * 调用接口同步华盛内部系统服务顾问绑定
     * @param eliteBean
     * @param Customerid
     * @param r_Rolegroup_Id
     * @param r_Staff_Id
     * @return
     */
    public static boolean dealBindCustTOStaff(String Customerid, String r_Loginname) {

        boolean reFlag = true;

        try {
            String injson = "{\"hsNo\":\"" + Customerid + "\",\"managerId\":\"" + r_Loginname + "\",\"divideType\":0,\"divideNumber\":1}";
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json");
            def sysurl = getProperty.get("crmurl");//配置本地接口地址
            sysurl = sysurl + "aipHSTBindCounselor";
            def getResult = Util.doHttpPostUseHead(sysurl, injson, "UTF-8", 100000, 0, headMap);
            log.debug("绑定接口返回：" + getResult);

            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "result");
            log.debug("绑定接口返回code：" + code);
            if (code == "1") {
                reFlag = true;
            } else {
                reFlag = false;
            }
        } catch (Exception e) {
            log.error("绑定客户异常!", e);
            reFlag = false;
        }
        log.debug("reFlag：" + reFlag);
        return reFlag;
    }

    /**
     * 调用内部接口。同步绑定更新 涉及活动的客户
     */
    public static boolean dealActivityVerify(String hst_no, String register_id) {

        boolean reFlag = true;

        try {
            String injson = "{\"hst_no\":\"" + hst_no + "\",\"register_id\":\"" + register_id + "\"}";
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json");
            def sysurl = getProperty.get("crmurl");//配置本地接口地址
            sysurl = sysurl + "aipHSTActivityVerify";
            def getResult = Util.doHttpPostUseHead(sysurl, injson, "UTF-8", 100000, 0, headMap);
            log.debug("活动复查绑定接口返回：" + getResult);

            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "resultcode");
            log.debug("活动复查绑定接口返回code：" + code);
            if (code == "1") {
                reFlag = true;
            } else {
                reFlag = false;
            }
        } catch (Exception e) {
            log.error("活动复查绑定客户异常!", e);
            reFlag = false;
        }
        log.debug("reFlag：" + reFlag);
        return reFlag;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }
}